//
//  ContentView.swift
//  ZipTool
//
//  Created by jerry on 2025/8/15.
//

import SwiftUI
import AppKit
import UniformTypeIdentifiers

struct ContentView: View {
    @State private var selectedTab = 0
    
    var body: some View {
        TabView(selection: $selectedTab) {
            ExtractionView()
                .tabItem {
                    Image(systemName: "archivebox")
                    Text("解压")
                }
                .tag(0)
            
            CompressionView()
                .tabItem {
                    Image(systemName: "plus.rectangle.on.folder")
                    Text("压缩")
                }
                .tag(1)
        }
        .frame(minWidth: 600, minHeight: 500)
    }
}

struct ExtractionView: View {
    @StateObject private var archiveManager = SimpleArchiveManager()
    @State private var isTargeted = false
    @State private var showingFilePicker = false
    @State private var showingFolderPicker = false
    @State private var extractionProgress: Double = 0
    @State private var isExtracting = false
    @State private var showingSuccessAlert = false
    
    var body: some View {
        VStack(spacing: 0) {
            if !archiveManager.entries.isEmpty {
                // 压缩包内容列表
                archiveContentView
                
                Spacer()
                
                // 解压按钮
                extractButton
            } else if archiveManager.isLoading {
                ProgressView("正在读取压缩包...")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            } else {
                // 空白界面，仅显示中央提示
                emptyDropZone
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding()
        .navigationTitle("解压工具")
        .alert("错误", isPresented: .constant(archiveManager.errorMessage != nil)) {
            Button("确定") {
                archiveManager.errorMessage = nil
            }
        } message: {
            Text(archiveManager.errorMessage ?? "")
        }
        .alert("解压完成", isPresented: $showingSuccessAlert) {
            Button("确定") { }
        } message: {
            Text("压缩包已成功解压到指定目录")
        }
        .fileImporter(
            isPresented: $showingFilePicker,
            allowedContentTypes: FileTypeHelper.supportedArchiveTypes
        ) { result in
            switch result {
            case .success(let url):
                archiveManager.loadArchive(from: url)
            case .failure(let error):
                archiveManager.errorMessage = "选择文件失败: \(error.localizedDescription)"
            }
        }
        .fileImporter(
            isPresented: $showingFolderPicker,
            allowedContentTypes: [.folder]
        ) { result in
            switch result {
            case .success(let url):
                extractToFolder(url)
            case .failure(let error):
                archiveManager.errorMessage = "选择目录失败: \(error.localizedDescription)"
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .openArchive)) { _ in
            openFilePanel()
        }
    }
    
    // MARK: - 视图组件
    
    private var emptyDropZone: some View {
        Button(action: {
            openFilePanel()
        }) {
            ZStack {
                Color.clear
                
                VStack(spacing: 16) {
                    RoundedRectangle(cornerRadius: 12)
                        .fill(isTargeted ? Color.blue.opacity(0.2) : Color.gray.opacity(0.1))
                        .stroke(
                            isTargeted ? Color.blue : Color.gray.opacity(0.3),
                            style: StrokeStyle(lineWidth: 2, dash: [10])
                        )
                        .frame(width: 200, height: 200)
                        .overlay {
                            VStack(spacing: 12) {
                                Image(systemName: "archivebox")
                                    .font(.system(size: 48))
                                    .foregroundColor(isTargeted ? .blue : .gray)
                                
                                Text(isTargeted ? "释放文件以打开" : "请选择压缩文件")
                                    .font(.headline)
                                    .foregroundColor(isTargeted ? .blue : .gray)
                                
                                Text("或拖拽文件到此处")
                                    .font(.subheadline)
                                    .foregroundColor(.secondary)
                                
                                Text("支持 ZIP、7Z、TAR、TAR.GZ、RAR 格式")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            .padding()
                        }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onDrop(of: [.fileURL], isTargeted: $isTargeted) { providers in
            guard let provider = providers.first else { return false }
            
            provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { data, error in
                guard let data = data as? Data,
                      let url = URL(dataRepresentation: data, relativeTo: nil) else {
                    return
                }
                
                DispatchQueue.main.async {
                    archiveManager.loadArchive(from: url)
                }
            }
            return true
        }
    }
    
    private var archiveContentView: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("压缩包内容")
                    .font(.headline)
                Spacer()
                Text("\(archiveManager.entries.count) 个项目")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            List(archiveManager.entries, id: \.name) { entry in
                Button(action: {
                    openEntry(entry)
                }) {
                    HStack {
                        Image(systemName: entry.isDirectory ? "folder.fill" : "doc.fill")
                            .foregroundColor(entry.isDirectory ? .blue : .gray)
                            .frame(width: 20)
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(entry.name)
                                .font(.system(.body, design: .monospaced))
                            
                            HStack {
                                if !entry.isDirectory {
                                    Text(FileTypeHelper.formatFileSize(entry.size))
                                        .font(.caption)
                                        .foregroundColor(.secondary)
                                }
                                
                                if let date = entry.modificationDate {
                                    Text(date, style: .date)
                                        .font(.caption)
                                        .foregroundColor(.secondary)
                                }
                            }
                        }
                        
                        Spacer()
                    }
                    .padding(.vertical, 2)
                }
                .buttonStyle(PlainButtonStyle())
                .disabled(entry.isDirectory)
            }
            .listStyle(PlainListStyle())
            .frame(maxHeight: 300)
        }
    }
    
    
    private var extractButton: some View {
        VStack(spacing: 12) {
            if isExtracting {
                VStack(spacing: 8) {
                    ProgressView(value: extractionProgress)
                        .progressViewStyle(LinearProgressViewStyle())
                    
                    Text("解压中... \(Int(extractionProgress * 100))%")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            Button(action: {
                showingFolderPicker = true
            }) {
                HStack {
                    Image(systemName: "arrow.down.circle.fill")
                    Text("选择目录并解压")
                }
                .font(.headline)
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.blue)
                .cornerRadius(10)
            }
            .disabled(isExtracting)
        }
    }
    
    // MARK: - 方法
    
    private func openEntry(_ entry: SimpleArchiveEntry) {
        archiveManager.extractEntry(named: entry.name) { url in
            guard let url = url else {
                DispatchQueue.main.async {
                    archiveManager.errorMessage = "无法打开该文件"
                }
                return
            }
            
            // 在主线程使用系统默认应用打开临时文件
            DispatchQueue.main.async {
                NSWorkspace.shared.open(url)
            }
        }
    }
    
    private func extractToFolder(_ destinationURL: URL) {
        isExtracting = true
        extractionProgress = 0
        
        archiveManager.extractArchive(to: destinationURL) { progress in
            extractionProgress = progress
            
            if progress >= 1.0 {
                isExtracting = false
                showingSuccessAlert = true
            }
        }
    }
    
    private func openFilePanel() {
        let panel = NSOpenPanel()
        panel.canChooseFiles = true
        panel.canChooseDirectories = false
        panel.allowsMultipleSelection = false
        panel.allowedContentTypes = FileTypeHelper.supportedArchiveTypes
        if panel.runModal() == .OK, let url = panel.url {
            archiveManager.loadArchive(from: url)
        }
    }
}

#Preview {
    ContentView()
}
